<template>
  <div class="tablePageWarp" style="padding: 0">
    <!-- 搜索 -->
    <detail-task-search-warp
      :taskId="taskId"
      :type="type"
      :queryParams="queryParam"
      @showAddCar="showAddCar"
      @search="refreshData"
      @clear="clearCondition"
      style="margin-bottom: 24px"
      @batchDelete="batchDelete"
      :loading="loading"
      :isUseBatchDelete="useBatchDelete"
      :upgradeTriggerType="upgradeTriggerType"
    ></detail-task-search-warp>
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :dataSource="dataArray"
      :showFilter="false"
      :scrollX="900"
      class="h100"
      :rowClassName="rowClassName"
      :row-selection="rowSelection"
    >
      <template slot="vin" slot-scope="text, record">
        <div class="withTextAndTagTd">
          <div class="tdText">
            <table-ellipsis :text="text"></table-ellipsis>
          </div>
          <lock-risk-jump
            :config="{
              lockFlag: record.lockFlag,
              compatibleRisk: record.compatibleRisk,
              taskJump: record.taskJump,
              query: { taskId: record.taskId, vehicleId: record.vehicleId },
            }"
          >
          </lock-risk-jump>
        </div>
      </template>
      <template slot="importBatch" slot-scope="text">
        <table-ellipsis :text="text"></table-ellipsis>
      </template>
      <template slot="importTime" slot-scope="text">
        <table-ellipsis :text="text ? $options.filters.moment(text) : '_'"></table-ellipsis>
      </template>
      <template slot="vehicleType" slot-scope="text">
        <table-ellipsis :text="$t(vehicleTypeObj[text])"></table-ellipsis>
      </template>
      <template slot="taskVehicleAppointTimeList" slot-scope="text">
        <table-ellipsis :tableEllipsisIsTurnLine="false" :text="text" ></table-ellipsis>
      </template>
      <template slot="startTime" slot-scope="text">
        <table-ellipsis :text="text ? $options.filters.moment(text) : '_'"></table-ellipsis>
      </template>
      <template slot="updateTime" slot-scope="text">
        <table-ellipsis :text="text ? $options.filters.moment(text) : '_'"></table-ellipsis>
      </template>
      <template slot="upgradeStatus" slot-scope="text">
        {{ operationStatusObj[text] }}
      </template>
      <span slot="status" slot-scope="text, record">{{ taskVehicleStatusObjText[record.status] }}</span>
      <template slot="vehicleModel" slot-scope="text">
        <table-ellipsis :text="text"></table-ellipsis>
      </template>
      <template slot="stereotype" slot-scope="text">
        <table-ellipsis :text="text"></table-ellipsis>
      </template>
      <span slot="action" slot-scope="text, record" class="tableOperateSty">
        <template v-if="record.deleted">-</template>
        <operation-menu
          v-else
          :menus="getTbRowMenus(record)"
          @clickaction="
            (key) => {
              doAction(key, record)
            }
          "
        ></operation-menu>
      </span>
    </s-table>
    <!-- 零件升级详情 -->
    <ecu-update-detail-dialog
      v-if="partDialogQuery"
      ref="ecuUpdateDetailDialogRef"
      height="70vh"
      width="80%"
      :query="partDialogQuery"
    ></ecu-update-detail-dialog>
    <!-- 应用详情 -->
    <app-update-detail-dialog
      v-if="appDialogQuery"
      ref="appUpdateDetailDialogRef"
      height="60vh"
      width="70%"
      :query="appDialogQuery"
    ></app-update-detail-dialog>
    <!-- 异常日志 -->
    <part-update-exception-log-dialog
      v-if="exceptionDialogQuery"
      ref="partUpdateExceptionLogDialog"
      height="60vh"
      width="60%"
      :query="exceptionDialogQuery"
    ></part-update-exception-log-dialog>
    <!-- 添加车辆 -->
    <a-modal
      v-if="showAddCar"
      :width="1200"
      :title="$t('addcar')"
      v-model="addCarModelVisible"
      :confirmLoading="addCarConfirmLoading"
      :destroyOnClose="true"
      :keyboard="false"
      :maskClosable="false"
      centered
      :bodyStyle="bodyStyle"
      @ok="saveAddCar"
    >
      <add-car-to-task ref="addcartotask" dataAdress="detailAddCar" :showFileOnly=true></add-car-to-task>
    </a-modal>
  </div>
</template>
<script>

import moment from 'moment'

import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { mapState, mapMutations } from 'vuex'
import OperationMenu from '@/components/OperationMenu'
import EcuUpdateDetailDialog from '@/views/components/EcuUpdateDetail/dialog.vue'
import PartUpdateExceptionLogDialog from '@/views/components/PartUpdateExceptionLog/dialog.vue'
import AppUpdateDetailDialog from '@/views/components/OneAppUpdateDetail/dialog.vue'
import { STable } from '@/components'
import AddCarToTask from './AddCarToTask.vue'
import DetailTaskSearchWarp from './DetailTaskSearchWarp.vue'
import lodash from 'lodash'
import LockRiskJump from '@/views/components/CustomTag/lockRiskJump.vue'
import { detailTaskExecutiveColumns } from '../config'
const orinQueryParam = {
  // 开始时间最小值
  startTimeGe: null,
  // 开始时间最大值
  startTimeLe: null,
  // 更新时间最小值
  updateTimeGe: null,
  // 更新时间最大值
  updateTimeLe: null,
  // 导入时间最小值
  importTimeGe: null,
  // 导入时间最大值
  importTimeLe: null,
  // 预约时间最小值
  taskVehicleAppointTimeGe: null,
  // 预约时间最大值
  taskVehicleAppointTimeLe: null,
  // 导入批次号
  importBatch: null,
  upgradeStatus: [],
  status: []
}
export default {
  name: 'ExecutiveInformation',
  props: {
    taskId: {
      type: String,
      default: ''
    },
    // 1用户升级 2自动升级
    type: {
      type: Number,
      default: 1
    },
    taskStatus: {
      type: Number,
      required: true
    },
    upgradeTriggerType: {
      type: String,
      default: ''
    }
  },
  components: {
    DetailTaskSearchWarp,
    TableEllipsis,
    OperationMenu,
    EcuUpdateDetailDialog,
    PartUpdateExceptionLogDialog,
    AppUpdateDetailDialog,
    AddCarToTask,
    STable,
    LockRiskJump
  },
  data () {
    return {
      columns: this.type==2?detailTaskExecutiveColumns:detailTaskExecutiveColumns.filter(item=>item.dataIndex!=='factoryRetryCount'),
      // 查询参数
      queryParam: lodash.cloneDeep(orinQueryParam),
      recordData: {},
      // 查看零件详情的搜索条件
      partDialogQuery: null,
      // 查看异常日志的搜索条件
      exceptionDialogQuery: null,
      // 查看应用详情搜索条件
      appDialogQuery: null,
      addCarModelVisible: false,
      addCarConfirmLoading: false,
      selectedRowKeys: [],
      loading: false,
      bodyStyle: { height: '1000px' },
      enableAddCarAudit: true,
      currentStatus: null,
      dataArray: [],
    }
  },
  computed: {
    ...mapState({
      taskEcuUpdateDictCode: (state) => state.dict.taskEcuUpdateDictCode,
      detailAddCar: (state) => state.newTask.detailAddCar,
      instantUpdateTime: (state) => state.app.instantUpdateTime
    }),
    vehicleTypeObj () {
      return this.$store.getters.vehicleTypeObj()
    },
    taskVehicleStatusObjText () {
      return this.$store.getters.getDictCodeObj('taskVehicleStatusDictCode')
    },
    operationStatusObj () {
      return this.$store.getters.getTaskDictCodeObj('operationStatus')
    },
    tbRowMenus () {
      const vm = this
      return [
        {
          title: this.$t('sjxq'),
          key: 'partUpdateDetail'
        },
        {
          title: this.$t('exceptionLog'),
          key: 'exceptionLog'
        },
        // sota测试任务
        // {
        //   title: this.$t('applicationDetail'),
        //   key: 'applicationDetail',
        // },
        {
          title: this.$t('ztsj'),
          key: 'ztsj',
          // 暂停升级(上报状态为未开始1或者进行中2且操作状态为正常时且任务状态为12)
          disabled (record) {
            return !(
              (record.status === 1 || record.status === 2) &&
              record.upgradeStatus === 1 &&
              vm.taskStatus === 12
            )
          }
        },
        {
          title: this.$t('cancelUpgrade'),
          key: 'cancelUpgrade',
          // 取消升级 上报状态为未开始1或者进行中2且操作状态为正常且任务状态为12才有
          disabled (record) {
            return !(
              (record.status === 1 || record.status === 2) &&
              record.upgradeStatus === 1 &&
              vm.taskStatus === 12
            )
          }
        },
        {
          title: this.$t('resumeUpgrade'),
          key: 'renewUpgrade',
          // 恢复升级 操作状态为暂停升级2才有
          disabled (record) {
            return !(record.upgradeStatus === 2 && vm.taskStatus === 12)
          }
        }
      ]
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys,selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
        }
      }
    },
    useBatchDelete(){
      return this.selectedRowKeys.length === 0
    }
  },
  mounted () {
    this.getPageDictData()
    this.loadData()
  },
  methods: {
    ...mapMutations(['RESET_ADDCAR']),
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      JnqueryParam.taskId = vm.taskId
      vm.$api.getTaskVehiclePageData({ ...parameter, ...JnqueryParam }).then(res => {
        this.dataArray = res.data
      })
    },
    getTaskInfor () {
      const vm = this
      return new Promise((resolve, reject) => {
        vm.$api
          .getTaskInfor({ id: vm.taskId })
          .then((res) => {
            vm.$set(vm.detailAddCar, 'modelId', res.data.modelId)
            vm.$set(vm.detailAddCar, 'strategyId', res.data.strategyId)
            vm.$set(vm.detailAddCar, 'taskId', vm.taskId)
            this.currentStatus = res.data.status

            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    getIsEnableAddCarAudit() {
      const vm = this
      return new Promise((resove,reject) => {
        vm.$api.getIsEnableAddCarAudit().then((res)=>{
            vm.$set(vm.detailAddCar, 'enableAddCarAudit', res.data)
            this.enableAddCarAudit = res.data
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取操作每行的菜单
    getTbRowMenus (record) {
      return this.tbRowMenus.filter((item) => {
        return !(item.disabled && item.disabled(record))
      })
    },
    // 列表操作
    doAction (key, record) {
      const vm = this
      vm.recordData = record
      if (key === 'partUpdateDetail') {
        this.showEcuUpdateDetail()
      } else if (key === 'applicationDetail') {
        this.showAppUpdateDetail()
      } else if (key === 'exceptionLog') {
        vm.showEcuExceptionDetail()
      } else {
        // 取消升级或暂停升级
        vm.upgradeStatusTaskCars(key)
      }
    },
    // 查看零件详情
    showEcuUpdateDetail () {
      this.$router.push({path:"/statistics/monitorList","query":{
         vin: this.recordData.vin,
         taskId: this.recordData.taskId
       }})
    },
    // 查看异常日志
    showEcuExceptionDetail () {
      this.exceptionDialogQuery = {
        vehicleId: this.recordData.vehicleId,
        taskIds:this.recordData.taskId
      }
      console.log(this.exceptionDialogQuery);

      this.$nextTick(() => {
        this.$refs.partUpdateExceptionLogDialog.switchVisible(true)
      })
    },
    // 查看应用详情
    showAppUpdateDetail () {
      const vm = this
      this.appDialogQuery = {
        vehicleId: vm.recordData.vehicleId,
        softwareDid: vm.recordData.softwareDid,
        taskIds: vm.recordData.taskId
      }
      this.$nextTick(() => {
        this.$refs.appUpdateDetailDialogRef.switchVisible(true)
      })
    },
    // 暂停 取消升级 恢复升级
    upgradeStatusTaskCars (key) {
      const vm = this
      let upgradeStatus = 0
      if (key === 'ztsj') {
        upgradeStatus = 2
      } else if (key === 'cancelUpgrade') {
        upgradeStatus = 3
      } else if (key === 'renewUpgrade') {
        upgradeStatus = 1
      }
      this.$confirm({
        title: vm.$t('systemTip'),
        content: vm.$t('taskVehicleUpgradeActionTip').replace('__CONTENT__', vm.$t(key)) + `[${vm.recordData.vin}]?`,
        onOk () {
          vm.$api
            .upgradeStatusTaskCars({
              taskId: [vm.recordData.taskId],
              taskVehicleId: vm.recordData.vehicleId,
              upgradeStatus
            })
            .then(() => {
              vm.$message.success(vm.$t('successfullyOperation'))
              vm.refreshData()
            })
        },
        onCancel () {}
      })
    },
    showAddCar (value) {

      this.RESET_ADDCAR()
      this.getIsEnableAddCarAudit()

      if(this.enableAddCarAudit) {
          this.bodyStyle = { height: '1000px' }
      }else{
          this.bodyStyle = { height: '600px' }
      }
      this.getTaskInfor().finally(() => {
          if(this.currentStatus != 12) {
              this.$message.error('当前任务未生效，无法追加车辆')
              return
          }
          this.detailAddCar.choseType = 2
          this.addCarModelVisible = value
      })


    },
    batchDelete() {
      const vm = this
      if(vm.selectedRowKeys.length == 0){
          vm.$message.error('无勾选车辆！')
          return
      }
      const params = {
        ids: vm.selectedRowKeys
      }
      let tempDeleteName = []
      this.dataArray.forEach(e => {
        if (vm.selectedRowKeys.includes(e.id)) {
          tempDeleteName.push(e.vin)
        }
      })
      this.$confirm({
        title: '批量删除任务车辆',
        content: `是否继续删除已勾选车辆？（${tempDeleteName.join('，')}）`,
        onOk () {
          vm.loading = true
          vm.$api.batchDeleteTaskVehicle(vm.taskId,params)
          .then(()=>{
            vm.loading = false
            vm.$message.success(vm.$t('successfullyOperation'))
            vm.refreshData()


          }).finally(()=>{
            vm.loading = false
          })
        },
        onCancel () {}
      })


    },
    // 添加车辆保存
    saveAddCar () {

      const vm = this
      const params = {
        taskId: vm.taskId
      }
      if (vm.detailAddCar.choseType === 2) {
        // 来自文件
        params.vehicleSourceType = 3
        //   文件预处理
        params.pretreatmentId = vm.detailAddCar.pretreatmentId
        params.startTime = moment(vm.detailAddCar.queryParam.startTime).format('YYYY-MM-DD HH:mm:ss')
        params.endTime = moment(vm.detailAddCar.queryParam.endTime).format('YYYY-MM-DD HH:mm:ss')

      } else if (vm.detailAddCar.choseType === 1) {
        // 批量选择
        if (vm.detailAddCar.isSlefSelect) {
          // 自定义勾选
          params.vehicleSourceType = 2
          // 自定义勾选车辆ids
          params.vehicleIds = vm.detailAddCar.selectCarIds
        } else {
          // 批量全部
          params.vehicleSourceType = 1
          // 筛选车辆类型 省份 vin
          params.vehicleType = vm.detailAddCar.queryParam.vehicleType
          params.province = vm.detailAddCar.queryParam.province
          params.vin = vm.detailAddCar.queryParam.vin
        }
      }

      vm.$refs.addcartotask.$refs.ruleForm.validate(() => {
        if(!vm.detailAddCar.queryParam.startTime || !vm.detailAddCar.queryParam.endTime){
           this.$message.error("请填写正确有效期")
            return
        } 
         if(vm.detailAddCar.pretreatmentId){
           vm.$refs.addcartotask.$refs.ruleForm.clearValidate('fileName')
        }else{
              this.$message.error("请上传文件")
              return
        }
          if(this.enableAddCarAudit) {
                const auditConfigData = vm.$refs.addcartotask.$refs.auditProcessRef.getConfigsData()
                if (auditConfigData.length === 0) {
                  return
                }
                params.candidates = auditConfigData === 'noNeedRole' ? [] : auditConfigData
          }
          vm.addCarConfirmLoading = true
                vm.$api
                  .increaseTaskCars(params)
                  .then(() => {
                    vm.addCarModelVisible = false
                    if(vm.detailAddCar.enableAddCarAudit){
                        vm.$message.success('操作成功，请等待审批，审批成功后才会显示车辆信息')
                    }else {
                        vm.$message.success('操作成功')
                    }

                    // vm.$refs.table.refresh() // 刷新列表
                    vm.refreshData()
                  })
                  .finally(() => {
                    vm.addCarConfirmLoading = false
                  })
      })
    },
    refreshData () {
      // this.$refs.table.refresh(bool)
      // this.$refs.table.clearSelected()
      this.loadData()
    },
    getPageDictData () {
      ;['getTaskEcuUpdateDictCodeData', 'getTaskVehicleStatusDictCodeData'].forEach((method) => {
        this.$store.dispatch(method)
      })
    },
    clearCondition () {
      this.queryParam = lodash.cloneDeep(orinQueryParam)
      console.log(this.queryParam, 'queryParam')
      this.refreshData()
    },
    rowClassName (record) {
      return record.deleted ? 'rowRemoved' : ''
    }
  },
  watch: {
    // 重新请求数据
    instantUpdateTime () {
      this.queryParam = lodash.cloneDeep(orinQueryParam)
      this.refreshData()
    }
  }
}
</script>
